import axios from "axios";
import store from "../store";
import { getToken } from "./auth";
import {Message} from "element-ui";

const server = axios.create({
    baseURL:'/vueAdmin',
    timeout:5000
})

server.interceptors.request.use(
    config => {
        //token前台验证信息
        if(store.getters.token){
            config.headers['Authorization'] = `Bearer ${getToken()}`
        }
        return config
},
    error => {

        return Promise.reject(error)

    }
)

server.interceptors.response.use(
    response=>{
        const res = response.data
        if(res.code !== 0){
            Message({
                message:res.msg || "请求失败",
                type: 'error',
                duration: 5 * 1000
            })
            // if(res.code === -2){
            //
            // }
            return Promise.reject(new Error(res.msg || '请求失败'))
        }else{
            return res
        }
    },
    error => {
        console.log({error})
        const { msg } = error.response.data
            Message({
                message:msg || '请求失败',
                type:'error',
                duration: 5 * 1000
            })
        return Promise.reject(error)
    }
)
export default server
